package com.yzf.utils;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.regex.Pattern;

import org.springframework.util.DigestUtils;


public class TextUtil {

	public static boolean isEmpty(String str) {
		if (str == null)
			return true;
		if (str.equals(""))
			return true;
		return false;
	}

	public static boolean isNotEmpty(String str) {
		if (str == null)
			return false;
		if (str.equals(""))
			return false;
		if (str.trim().equals(""))
			return false;
		return true;
	}

	public static boolean isEmpty(Double doub) {
		if (doub == null)
			return true;
		if (doub <= 0)
			return true;
		return false;
	}

	public static boolean isNotEmpty(Double doub) {
		if (doub == null)
			return false;
		if (doub <= 0)
			return false;
		return true;
	}

	public static boolean isEmpty(Integer inte) {
		if (inte == null)
			return true;
		return false;
	}

	public static boolean isNotEmpty(Integer inte) {
		if (inte == null)
			return false;
		return true;
	}

	public static boolean isEmpty(Object object) {
		if (object == null)
			return true;
		return false;
	}

	public static boolean isNotEmpty(Object object) {
		if (object == null)
			return false;
		return true;
	}

	public static Integer emptyToZero(Integer object) {
		return object == null ? 0 : object;
	}

	public static boolean isGtZero(Integer object) {
		if (object == null)
			return false;
		if (object <= 0)
			return false;
		return true;
	}

	public static String toString(String str) {
		return str == null ? "" : str;
	}

	public static String listConvertToCommaSeparateColumnString(List list) {
		StringBuffer sb = new StringBuffer();
		if (list.size() > 0) {
			for (Object item : list) {
				String str = (String) item;
				sb.append(str).append(",");
			}
			return sb.substring(0, sb.length() - 1);
		}
		return "";
	}

	public static String listConvertToCommaSeparateValueString(List list) {
		StringBuffer sb = new StringBuffer();
		if (list.size() > 0) {
			for (Object item : list) {
				String str = (String) item;
				if (TextUtil.isNumeric(str)) {
					sb.append(str).append(",");
				} else {
					sb.append("'").append(str).append("'").append(",");
				}
			}
			return sb.substring(0, sb.length() - 1);
		}
		return "";
	}

	public static boolean isNumeric(String str) {
		Pattern pattern = Pattern.compile("([0-9]|[.])*");
		return pattern.matcher(str).matches();
	}

	public static String encoding(String str) {
		try {
			byte[] b = str.getBytes("iso8859-1");
			for (int j = 0; j < b.length; j++) {
				byte b1 = b[j];
				if (b1 == 63) {
					break; // 1
				} else if (b1 > 0) {
					continue;// 2
				} else if (b1 < 0) { // 不可能为0，0为字符串结束符 小于0乱码
					str = new String(b, "UTF-8");
					break;
				}
			}
			return str;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return "";
		}
	}

	public static String getEncoding(String str) {
		String encode = "GB2312";
		try {
			if (str.equals(new String(str.getBytes(encode), encode))) {
				String s = encode;
				return s;
			}
		} catch (Exception exception) {
		}
		encode = "ISO-8859-1";
		try {
			if (str.equals(new String(str.getBytes(encode), encode))) {
				String s1 = encode;
				return s1;
			}
		} catch (Exception exception1) {
		}
		encode = "UTF-8";
		try {
			if (str.equals(new String(str.getBytes(encode), encode))) {
				String s2 = encode;
				return s2;
			}
		} catch (Exception exception2) {
		}
		encode = "GBK";
		try {
			if (str.equals(new String(str.getBytes(encode), encode))) {
				String s3 = encode;
				return s3;
			}
		} catch (Exception exception3) {
		}
		return "";
	}

	public static String dateToString(Date date) {
		if (!TextUtil.isEmpty(date)) {
			String str = null;
			DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			str = format.format(date);
			return str;
		}
		return "";

	}

	public static Date stringToDate(String str) {
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		Date date = null;
		try {
			date = format.parse(str);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		date = java.sql.Date.valueOf(str);

		return date;
	}

	public static String dateTimeToString(Date date) {
		if (isEmpty(date)) {
			return "";
		} else {
			SimpleDateFormat df = new SimpleDateFormat(
					"yyyy-MM-dd HH:MM:ss.SSS");
			java.sql.Date sdate = new java.sql.Date(date.getTime());
			String strDate = df.format(sdate);
			return strDate;
		}
	}

	public static Date stringToDateAndTime(String str) {
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
		Date date = null;
		try {
			date = format.parse(str);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return date;
	}

	public static String digestMd5(String password) {
		if (TextUtil.isNotEmpty(password)) {
			return DigestUtils.md5DigestAsHex(password.getBytes());
		} else {
			return "";
		}
	}

	public static Integer[] stringArrayToIntArray(String[] stringArray) {
		Integer[] intArry = new Integer[stringArray.length];
		for (int i = 0; i < intArry.length; i++) {
			intArry[i] = Integer.parseInt(stringArray[i]);
		}
		return intArry;
	}

	public static String[] intersect(String[] arr1, String[] arr2) {
		Map<String, Boolean> map = new HashMap<String, Boolean>();
		LinkedList<String> list = new LinkedList<String>();
		for (String str : arr1) {
			if (!map.containsKey(str)) {
				map.put(str, Boolean.FALSE);
			}
		}
		for (String str : arr2) {
			if (map.containsKey(str)) {
				map.put(str, Boolean.TRUE);
			}
		}

		for (Entry<String, Boolean> e : map.entrySet()) {
			if (e.getValue().equals(Boolean.TRUE)) {
				list.add(e.getKey());
			}
		}

		String[] result = {};
		return list.toArray(result);
	}

	public static String[] minus(String[] arr1, String[] arr2) {
		LinkedList<String> list = new LinkedList<String>();
		LinkedList<String> history = new LinkedList<String>();
		String[] longerArr = arr1;
		String[] shorterArr = arr2;
		// 找出较长的数组来减较短的数组
		if (arr1.length > arr2.length) {
			longerArr = arr2;
			shorterArr = arr1;
		}
		for (String str : longerArr) {
			if (!list.contains(str)) {
				list.add(str);
			}
		}
		for (String str : shorterArr) {
			if (list.contains(str)) {
				history.add(str);
				list.remove(str);
			} else {
				if (!history.contains(str)) {
					list.add(str);
				}
			}
		}

		String[] result = {};
		System.out.println("minusLength:" + list.toArray(result).length);
		return list.toArray(result);
	}

	public static String unitsAddZero(Integer units) {
		if (!TextUtil.isEmpty(units) && units <= 9) {
			return "0" + units;
		}
		return TextUtil.isEmpty(units) ? null : units.toString();
	}

	public static String removeEndDot(String idList) {
		if (idList.length() > 1) {
			idList.substring(0, idList.length() - 1);
			return idList;
		}
		return "";
	}

	public static String cognosUrlToGroupName(String url) {
		try {
			String urldecoder = URLDecoder.decode(url, "UTF-8");
			return urldecoder
					.substring(
							urldecoder.indexOf("content"),
							urldecoder.indexOf("']",
									urldecoder.indexOf("/report[@name='")))
					.replace("/folder[@name='", "_").replace("']", "")
					.replace("/report[@name='", "_");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return "";
		}
	}

	public static String getProperties(String propertiesFileName, String key) {
		Properties props = new Properties();
		try {
			String path = TextUtil.class.getResource("/").toString()
					.replace("file:/", "").replace("%20", " ")
					+ propertiesFileName;
			props.load(new FileInputStream(path));
			String value = props.getProperty(key);
			return value;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 创建指定数量的随机字符串
	 * 
	 * @param numberFlag
	 *            是否是数字
	 * @param length
	 * @return
	 */
	public static String createRandom(Boolean isNumber, Integer length) {
		String randomCode = "";
		String data = isNumber ? "1234567890" : "1234567890abcdefghijkmnpqrstuvwxyz";
		int len = data.length();
		boolean bDone = true;
		do {
			randomCode = "";
			int count = 0;
			for (int i = 0; i < length; i++) {
				double dblR = Math.random() * len;
				int intR = (int) Math.floor(dblR);
				char c = data.charAt(intR);
				if (('0' <= c) && (c <= '9')) {
					count++;
				}
				randomCode += data.charAt(intR);
			}
			if (count >= 2) {
				bDone = false;
			}
		} while (bDone);

		return randomCode;
	}

	public static void main(String[] args) {
			System.out.println(TextUtil.createRandom(true, 6));
	}
}
